<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item  prop="label">
        <el-input
          v-model="queryParams.label"
          placeholder="请输入学院/年级/专业班级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row style="margin-bottom: 5px">
      <el-col>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['stuManage:class:add']"
        >新增</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading" :data="levelOneEles"
      style="width: 100%"
      row-key="id"
      border
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
        prop="label"
        label="校区/学院/年级/专业班级">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.type!==1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['stuManage:dor:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.type!==1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['stuManage:dor:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--<pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
-->
    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="校区/学院/年级" prop="areaCollegeGradeProClass">
          <el-cascader
            style="width: 340px"
            v-model="form.areaCollegeGradeProClass"
            :options="classList"
            :props="casProps"
            @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item :label="label" prop="label" >
          <el-input v-model="form.label" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listClassTree, getClass, delClass, addClass, updateClass,findChildrenStuClassCasById,findAreaCollegeGrades,findChildrenById} from "@/api/stu/class";
  import {getUserRoleByUserId} from "@/api/stu/userRole";
  import {getInfo} from "@/api/login";


  export default {
    name: "Class",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 班级管理表格数据
        classList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageSize:null,
          parentId: null,
          label: null,
          value: null,
          schoolAreaIds:[],
          collegeIds:[],
          proClassIds:[],
          buildingIds:[],
          floorIds:[]
        },
        // 表单参数
        form: {
          type:null,
          parentLabel:'',
          parentId:'',
          collegeGradeProClass:''
        },
        // 表单校验
        rules: {
          parentId: [
            {required: true, message: "父级id不能为空", trigger: "blur"}
          ],
          label: [
            {required: true, message: "学院名或年级或专业班级名不能为空", trigger: "blur"}
          ],
          value: [
            {required: true, message: "学院名或年级或专业班级名不能为空", trigger: "blur"}
          ]
        },
        stuClassCasList: [],
        casProps:{
          label:'label',
          value:'id',
          checkStrictly: true
        },
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        userRoles: [],
        userId: null,
        isMultiRoles:false,
        levelOneEles:[],
        label:'',
        //是否为全校管理员
        isSchoolLevel:false
      };
    },
    created() {
      this.getUserInfo()
      // 添加班级时级联组件所需数据
      this.getStuClassTree()
    },
    methods: {
      // 添加或修改班级级联组件所选值变化
      handleChange(value) {
        this.handleLabel(value.length+1)
      },
      getUserInfo() {
        getInfo().then(res => {
          this.userId = res.user.userId
          this.getUserRoles()
        })
      },
      getUserRoles() {
        getUserRoleByUserId(this.userId).then(res => {
          this.userRoles = res.data
          if (this.userRoles.length > 1) {
            this.queryParams.isMultiRoles = true
            this.isMultiRoles = true
          }
          let isOldAdmin = false
          let isNewAdmin = false
          this.userRoles.forEach(item => {
            if (item.roleType === 1) this.queryParams.schoolAreaIds.push(item.roleId)
            if (item.roleType === 2) this.queryParams.collegeIds.push(item.roleId)
            if (item.roleType === 3) this.queryParams.proClassIds.push(item.roleId)
            if (item.roleType === 4) this.queryParams.buildingIds.push(item.roleId)
            if (item.roleType === 5) this.queryParams.floorIds.push(item.roleId)
            if (item.roleId === 1) isNewAdmin = true
            if (item.roleId === 2) isOldAdmin = true
          })
          if (isOldAdmin && isNewAdmin) {
            this.isSchoolLevel = true
          }
          this.getList()
        })
      },
      load(tree, treeNode, resolve) {
        this.loading = true;
        findChildrenById({id:tree.id}).then(res=>{
          resolve(res.data)
          this.loading = false;
        })
      },
      /** 查询班级管理列表 */
      getList() {
        this.loading = true;
        if (this.queryParams.collegeIds.length>0&&this.queryParams.proClassIds.length>0){
          this.queryParams.proClassIds=[]
        }
        // if (this.isSchoolLevel){
        //   this.queryParams.parentId=0
        // }
        listClassTree(this.queryParams).then(response => {
          this.levelOneEles=response.rows
          this.loading = false;
        });
      },
      getStuClassTree(){
        findAreaCollegeGrades().then(res=>{
          this.classList=res.data
        })
      },
      handleLabel(type){
        if (type===2) this.label='学院'
        if (type===3) this.label='年级'
        if (type===4) this.label='专业班级'
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          parentId: null,
          label: null,
          value: null,
          areaCollegeGradeProClass:[]
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.loading = true;
        listClassTree({label:this.queryParams.label}).then(response => {
          this.levelOneEles=response.rows
          this.loading = false;
        });
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.$tab.refreshPage()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.title = "添加";
        this.open = true;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getClass(id).then(response => {
          this.form = response.data;
          if (this.form.areaCollegeGradeProClass.length===4){
            this.form.areaCollegeGradeProClass=this.form.areaCollegeGradeProClass.slice(0,3)
          }
          this.handleLabel(this.form.type)
          this.title = "修改";
          this.open = true;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateClass(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                // 刷新当前页签
                this.$tab.refreshPage();
              });
            } else {
              addClass(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.$tab.refreshPage();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('确认删除【' + row.label + '】？').then(function () {
          return delClass(ids);
        }).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.$tab.refreshPage();
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('stuManage/class/export', {
          ...this.queryParams
        }, `class_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>

<style scoped>
</style>
